package com.xiongjie.routerFactory;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.AbstractUser;
import io.vertx.ext.auth.AuthProvider;

import javax.validation.constraints.NotNull;

public class SessionUser extends AbstractUser {

    private final JsonObject accessToken;

    public SessionUser(@NotNull JsonObject accessToken) {
        this.accessToken = accessToken;
    }

    @Override
    protected void doIsPermitted(String permission, Handler<AsyncResult<Boolean>> resultHandler) {
        JsonArray appRoles = accessToken
                .getJsonObject("resource_access")
                .getJsonArray("roles");
        boolean result = appRoles.contains(permission);

        resultHandler.handle(Future.succeededFuture(result));
    }

    @Override
    public JsonObject principal() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setAuthProvider(AuthProvider authProvider) {
        throw new UnsupportedOperationException();
    }


    /**
     * 标准模版--重写比较方法
     * <p>
     * permission的格式为  serviceName:role
     */
    protected void doIsPermitted2(String permission, Handler<AsyncResult<Boolean>> resultHandler) {
        String[] parts = permission.split(":");
        //1.是否拥有admin角色
        boolean hasRealmRole = accessToken
                .getJsonObject("realm_access", new JsonObject())
                .getJsonArray("roles", new JsonArray())
                .contains("admin");

        //2.是否拥有指定角色
        boolean hasApplicationRole;
        JsonObject adminRoles = accessToken
                .getJsonObject("resource_access", new JsonObject())
                .getJsonObject(parts[0]);
        if (adminRoles == null) {
            hasApplicationRole = false;
        } else {
            hasApplicationRole = adminRoles.getJsonArray("roles", new JsonArray())
                    .contains("admin");
        }

        //3.判断是否是admin的角色权限
        if (hasRealmRole || hasApplicationRole) {
            resultHandler.handle(Future.succeededFuture(Boolean.TRUE));
        }else{
            //4.判断是否拥有指定角色的权限
            boolean hasSpecialRole;
            JsonObject appRoles = accessToken
                    .getJsonObject("resource_access", new JsonObject())
                    .getJsonObject(parts[0]);
            if (appRoles == null) {
                hasSpecialRole = false;
            } else {
                hasSpecialRole = appRoles
                        .getJsonArray("roles", new JsonArray())
                        .contains(parts[1]);
            }
            resultHandler.handle(Future.succeededFuture(hasSpecialRole));
        }
    }
}
